#include "StdAfx.h"
#include "GeneticProcessInvoker.h"
#include <iostream>

GeneticProcessInvoker::GeneticProcessInvoker(std::ostream &str)
:m_str(str)
{
}

GeneticProcessInvoker::~GeneticProcessInvoker(void)
{
}

void GeneticProcessInvoker::DoEvolution(IGeneticProcess *process, unsigned int iterations)
{
	m_gp = process;
	m_iterationsToGo = iterations;
	m_totalIterations = iterations;

	std::cout << "Initializing... ";
	m_gp->Initialize();
	std::cout << "OK" << std::endl;

	std::cout << "Starting evolution..." << std::endl;
	while(m_iterationsToGo > 0)
	{
		m_gp->Select();
		std::cout << "Iteration: " << m_totalIterations - m_iterationsToGo + 1 << " / " << m_totalIterations << std::endl;
		std::cout << "Best: " << m_gp->GetBest(1) << std::endl;
		debug_process(false);
		m_gp->Mutate();
		m_gp->Crosover();
		m_iterationsToGo--;
	}
	m_gp->Select();

	debug_process(true);
	m_str << "3 best results: " << std::endl;
	m_str << m_gp->GetBest(3) << std::endl;
	std::cout << "Done" << std::endl;
}

void GeneticProcessInvoker::debug_process(bool all)
{
	m_str << "######################################" << std::endl;
	m_str << "Iteration: " << m_totalIterations - m_iterationsToGo + 1 << " / " << m_totalIterations << std::endl;
	if(all)
		m_str << m_gp->ToString() << std::endl;
	else
		m_str << "10 best results: " << std::endl << m_gp->GetBest(10) << std::endl;

}

void GeneticProcessInvoker::debug_results()
{
	debug_process(true);
}